<?php


namespace app\back\model;

use app\common\Image;
use think\facade\Db;
use think\response\Json;
use \Exception;

class CategoryModel
{
    private static $_table = 'category'; // 商品分类表
    private static $_tempTable = 'template'; // 模板表
    /**获取一二级分类列表以及模板
     * @param $info
     * @return Json
     */
    public static function lstFirAndSec($info)
    {
        $rtn = self::lstFirAndSecStatic($info);
        if (is_array($rtn)) return jsonSuccess('获取成功', $rtn);
        return $rtn;
    }

    /**获取一二级分类列表以及模板(内部调用)
     * @param $info
     * @param $id
     * @return array|Json
     */
    public static function lstFirAndSecStatic($info, $id = 0, $path = '')
    {
        try {
            // 获取一二级分类
            $map = [
                ['admin_id', '=', $info['id']],
                ['status', '=', 1],
                ['level', 'in', [0,1]]
            ];
            $field = 'id,name,pid';
            $cateInfo = Db::table(self::$_table)->where($map)->field($field)->select()->toArray();
            // 获取模板
            $mapRaw = "(`admin_id` = {$info['id']} OR is_system = 1) AND status = 1";
            $tempInfo = Db::table(self::$_tempTable)->field('id,name')->whereRaw($mapRaw)->select()->toArray();
            return  ['cateInfo' => getTree($cateInfo), 'tempInfo' => $tempInfo];
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**删除图片
     * @param $input
     * @param $info
     * @return Json
     */
    public static function delImg($input,$info)
    {
        try {
            //直接删除图片
            $basePath = app()->getRootPath();
            $filePath = explode('/', $input['pic']);
            unset($filePath[0]);
            unset($filePath[1]);
            unset($filePath[2]);
            unset($filePath[3]);
            $path = $basePath . implode('/', $filePath);
            if ($input['id'] !== null) {
                $map = [
                  ['id', '=', $input['id']],
                  ['admin_id', '=', $info['id']]
                ];
                $rtn = Db::table(self::$_table)->where($map)->update(['pic' => '']);
                if (!$rtn) {
                    return jsonFail('删除失败');
                }
            }
            @unlink($path);
            return jsonSuccess('删除成功');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**添加分类
     * @param $input
     * @param $info
     * @return Json
     */
    public static function add($input,$info)
    {
        try {
            if ($input['pid'] == '') {
                // 添加一级分类
                $pic = Image::uploadSingle($input['pic'],'category');
                if (!is_string($pic)) return $pic;
                $pic = $input['prefixUrl'] . '/api/uploads/' . str_replace('\\', '/', $pic);
                $input['path'] = '-0-';
                $input['level'] = 0;
                $input['pic'] = $pic;
                $input['template_id'] = 0;
            } else {
                $pid = explode(',', $input['pid']);
                $input['pid'] = array_pop($pid);
                $cateInfo = Db::table(self::$_table)->field('status,admin_id,level,path')->where('id', $input['pid'])->find();
                if (!$cateInfo) return jsonFail('未找到上级分类');
                if ($cateInfo['status'] != 1) return jsonFail('非启用的上级分类无法添加子分类');
                if ($cateInfo['admin_id'] != $info['id']) return jsonFail('非您添加的上级分类无法添加子分类');
                if ($cateInfo['level'] >=2) return jsonFail('三级分类及以下分类无法添加分类');
                $input['pic'] = '';
                $input['path'] = $cateInfo['path'] . $input['pid'] . '-';
                $input['level'] = $cateInfo['level'] + 1;
            }
            unset($input['prefixUrl']);
            $input['admin_id'] = $info['id'];
            $input['create_time'] = time();
            $input['status'] = 1;
            $rtn = Db::table(self::$_table)->insert($input);
            if ($rtn === 1) return jsonSuccess('添加成功');
            return jsonFail('添加失败');
        } catch (Exception $e) {
//            var_dump($e->getMessage());
            if ("SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '{$input['name']}' for key 'name'" == $e->getMessage()) return jsonFail('名字已存在');
            return jsonFail('服务内部错误~');
        }
    }

    /**获取分类列表
     * @param $input
     * @param $info
     * @return Json
     */
    public static function lst($input,$info)
    {
        try {
            // 搜索到的顶级分类
            $map[] = ['admin_id', '=', $info['id']];
            $map[] = ['level', '=', $input['level']];
            if ($input['status'] === '') {
                $map[] = ['status', 'in', [1,2]];
            } else {
                $map[] = ['status', '=', $input['status']];
            }
            if ($input['name'] !== '') {
                $map[] = ['name', 'like', "%{$input['name']}%"];
            }
            $rtn = Db::table(self::$_table)->where($map)->field('id,level,path')->order('create_time', 'desc')->select()->toArray();
            if (!$rtn) return jsonSuccess('暂无数据', ['count' => 0,'list' => []]);
            $ids = [];
            // 获取顶级分类id
            foreach ($rtn as $value) {
                if ($value['level'] == 0 && array_search($value['id'], $ids) === false) {
                    $ids[] = $value['id'];
                } else if ($value['level'] != 0) {
                    $str = explode('-', $value['path']);
                    if ($str[2] != '' && array_search($str[2], $ids) === false) {
                        $ids[] = $str[2];
                    }
                }
            }
            $count = count($ids);
            $searchIds = array_splice($ids,($input['page']-1) * $input['limit'], $input['limit']);
            if (!$searchIds) return jsonSuccess('暂无数据', ['count' => $count,'list' => []]);
            $path = '';
            foreach ($searchIds as $id) {
                $path .= "OR c.path LIKE '-0-{$id}-%'";
            }
            $ids = implode(',', $searchIds);
            $mapRaw = "c.status IN (1,2) AND (c.`id` IN ({$ids}) {$path})";
            $rtn = Db::table(self::$_table)->alias('c')
                ->leftJoin([self::$_tempTable => 't'], 't.id = c.template_id')
                ->field('c.id,c.name,c.pid,c.template_id, t.name as template_name, c.status,c.create_time,c.pic,c.level')->whereRaw($mapRaw)->order('c.create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => getTree($rtn)]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**删除分类
     * @param $input
     * @param $info
     * @return Json
     */
    public static function delete($input,$info)
    {
        try {
            // 获取当前信息
            $cateInfo = Db::table(self::$_table)->field('admin_id,status,level,path,pic,pid')->where('id', $input['id'])->find();
            if (!$cateInfo) return jsonFail('未找到分类信息');
            if ($cateInfo['admin_id'] != $info['id']) return jsonFail('该分类非您直接管理，您没有权限操作');
            if ($cateInfo['status'] == 3) return jsonFail('该分类已删除无法继续操作');
            // 根据不同status执行不同操作
            // 查询父级是否是启用
            if ($cateInfo['level'] != 0) {
                $fcateInfo = Db::table(self::$_table)->where('id', $cateInfo['pid'])->value('status');
                if (!$fcateInfo) return  jsonFail('为找到父级数据');
                if ($fcateInfo == 3) return jsonFail('父级数据已删除当前操作失败');
            }
            $update = ['status' => 3,'pic' => ''];
            if ($cateInfo['level'] == 2) {
                $mapRaw = 'admin_id = :admin_id AND `status` IN (1,2) AND (`id` = :id)';
                $mapRawData = ['admin_id'=>$info['id'],'id' => $input['id']];
            } else {
                $mapRaw = 'admin_id = :admin_id AND `status` IN (1,2) AND (`id` = :id OR path LIKE :path)';
                $mapRawData = ['admin_id'=>$info['id'],'id' => $input['id'], 'path' => "{$cateInfo['path']}{$input['id']}-%"];
            }
            $rtn = Db::table(self::$_table)->whereRaw($mapRaw, $mapRawData)->update($update);
            if ($rtn) {
                if ($cateInfo['level'] == 0) {
                    // 删除图片
                    $filePath = explode('/', $cateInfo['pic']);
                    unset($filePath[0]);
                    unset($filePath[1]);
                    unset($filePath[2]);
                    unset($filePath[3]);
                    Image::delete(app()->getRootPath() . '/' . implode('/', $filePath));
                }
                return jsonSuccess('操作成功');
            }
            return  jsonFail('数据没有更新，删除失败');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**修改状态
     * @param $input
     * @param $info
     * @return Json
     */
    public static function changeStatus($input,$info)
    {
        try {
            // 获取当前信息
            $cateInfo = Db::table(self::$_table)->field('admin_id,status,level,path,pid')->where('id', $input['id'])->find();
            if (!$cateInfo) return jsonFail('未找到分类信息');
            if ($cateInfo['admin_id'] != $info['id']) return jsonFail('该分类非您直接管理，您没有权限操作');
            if ($cateInfo['status'] == 3) return jsonFail('该分类已删除无法继续操作');
            // 根据不同status执行不同操作
            $update = ['status' => $input['status']];
            // 查询父级是否是启用
            if ($cateInfo['level'] != 0) {
                $fcateInfo = Db::table(self::$_table)->where('id', $cateInfo['pid'])->value('status');
                if (!$fcateInfo) return  jsonFail('未找到父级数据');
                if ($fcateInfo != 1) return jsonFail('父级数据禁用或已删除当前操作失败');
            }
            if ($input['status'] == 1) {
                // 启用
                $map = [
                    ['id', '=', $input['id']],
                    ['admin_id', '=', $info['id']],
                    ['status', '=', 2]
                ];
                $rtn = Db::table(self::$_table)->where($map)->update($update);
            } else {
                // 禁用
                if ($cateInfo['level'] == 2) {
                    $mapRaw = 'admin_id = :admin_id AND `status` = 1 AND (`id` = :id)';
                    $mapRawData = ['admin_id'=>$info['id'],'id' => $input['id']];
                } else {
                    $mapRaw = 'admin_id = :admin_id AND `status` = 1 AND (`id` = :id OR path LIKE :path)';
                    $mapRawData = ['admin_id'=>$info['id'],'id' => $input['id'], 'path' => "{$cateInfo['path']}{$input['id']}-%"];
                }
                $rtn = Db::table(self::$_table)->whereRaw($mapRaw, $mapRawData)->update($update);
            }
            if ($rtn) return jsonSuccess('修改成功');
            return  jsonFail('数据没有更新，修改失败');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取单个模板信息
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getOnly($input,$info)
    {
        try {
            // 获取当前信息
            $cateInfo = Db::table(self::$_table)->field('admin_id,status,id,name,level,template_id,pic')->where('id', $input['id'])->find();
            if (!$cateInfo) return jsonFail('未找到分类信息');
            if ($cateInfo['admin_id'] != $info['id']) return jsonFail('该分类非您直接管理，您没有权限操作');
            if ($cateInfo['status'] == 3) return jsonFail('该分类已删除无法继续操作');
            unset($cateInfo['admin_id']);
            unset($cateInfo['status']);
            $rtn = self::lstFirAndSecStatic($info,$input['id']);
            if (!is_array($rtn)) return $rtn;
            if ($cateInfo['template_id'] == 0) $cateInfo['template_id'] = '';
            return jsonSuccess('获取成功', ['info' =>$cateInfo, 'other' => $rtn]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**编辑分类信息
     * @param $input
     * @param $info
     * @return Json
     */
    public static function edit($input,$info)
    {
        try {
            // 获取当前信息
            // 获取当前信息
            $cateInfo = Db::table(self::$_table)->field('admin_id,status,id,name,pid,pic,path')->where('id', $input['id'])->find();
            if (!$cateInfo) return jsonFail('未找到分类信息');
            if ($cateInfo['admin_id'] != $info['id']) return jsonFail('该分类非您直接管理，您没有权限操作');
            if ($cateInfo['status'] == 3) return jsonFail('该分类已删除无法继续操作');
            if ($input['level'] == 0) {
                //修改为顶级
                $update['name'] = $input['name'];
                if ($input['pic']) {
                    $pic = Image::uploadSingle($input['pic'],'category');
                    if (!is_string($pic)) return $pic;
                    $update['pic'] = $input['prefixUrl'] . '/api/uploads/' . str_replace('\\', '/', $pic);
                    $rtn = Db::table(self::$_table)->where('id', $input['id'])->update($update);
                    if ($rtn) {
                        $filePath = explode('/', $cateInfo['pic']);
                        unset($filePath[0]);
                        unset($filePath[1]);
                        unset($filePath[2]);
                        unset($filePath[3]);
                        Image::delete(app()->getRootPath() . '/' . implode('/', $filePath));
                        return jsonSuccess('编辑成功');
                    }
                    return jsonFail('数据无变化，编辑失败');
                } else {
                    $rtn = Db::table(self::$_table)->where('id', $input['id'])->update($update);
                    if ($rtn) {
                        return jsonSuccess('编辑成功');
                    }
                    return jsonFail('数据无变化，编辑失败');
                }
            } else {
                $update = [
                    'name' => $input['name'],
                    'template_id' => $input['template_id']
                ];
                $rtn = Db::table(self::$_table)->where('id', $input['id'])->update($update);
                if ($rtn) {
                    return jsonSuccess('编辑成功');
                }
                return jsonFail('数据无变化，编辑失败');
            }
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }
}